package com.manage.modules.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.manage.common.core.domain.AjaxResult;
import com.manage.common.exception.CustomException;
import com.manage.framework.config.ServerConfig;
import com.manage.modules.utils.DateUtil;
import com.manage.modules.utils.UploadUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * 上传控制
 *
 * @author xu
 * 2021/8/18 17:34
 */
@RestController
public class UploadController {
    @Resource
    private ServerConfig serverConfig;

    @PostMapping("/uploadByPatent")
    public AjaxResult fault(@RequestParam("files") MultipartFile[] files, @RequestParam String parent) {
        if (files == null) {
            return AjaxResult.success();
        }
        JSONArray array = new JSONArray();
        for (MultipartFile file : files) {
            try {
                //获取上传时的文件名
                String fileName = DateUtil.getNowDateTime() + "_" + file.getOriginalFilename();
                String path = UploadUtil.upload(file, parent, fileName);
                String url = serverConfig.getUrl() + UploadUtil.getWebRelativeUrl(path);
                JSONObject object = new JSONObject();
                object.put("url", url);
                object.put("name", file.getOriginalFilename());
                object.put("local", path);
                array.add(object);
            } catch (IOException e) {
                throw new CustomException("上传失败");
            }
        }
        return AjaxResult.success(array);
    }
}
